App.Biz.CustomBiz = (function (App) {

    var _CUSTOMS_CACHE_KEY = 'ALL_CUSTOMS';
    var _Custom = App.Model.Custom;
    var _cache = App.Data.Cache;

    var loadCustomData = function () {
        var data = getstorage(_CUSTOMS_CACHE_KEY);
        var customs = [];
        if (data) {
            var list = JSON.parse(data);
            for (var i = 0; i < list.length; i++) {
                customs[i] = _Custom.buildFromJson(list[i]);
            }
        }
        return customs;
    };

    var saveCustomData = function (customs) {
        var data = JSON.stringify(customs);
        if (data) {
            setstorage(_CUSTOMS_CACHE_KEY, data);
            return true;
        }
        return false;
    };

    /**
     * 分组客户类型
     * @param customs
     */
    var computeCustomGroup = function (customs) {
        var groups = [];
        groups[_Custom.TYPE_THISMONTH] = [];
        groups[_Custom.TYPE_INTENTION] = [];
        groups[_Custom.TYPE_DEAL] = [];
        for (var i = 0; i < customs.length; i++) {
            _pushCustomToGroup(groups, customs[i]);
        }
        return groups;
    };

    var _pushCustomToGroup = function (groups, custom) {
        if (custom.isThisMonth()) {
            groups[_Custom.TYPE_THISMONTH].push(custom);
        }
        if (custom.isDeal()) {
            groups[_Custom.TYPE_DEAL].push(custom);
        }
        if (custom.isIntention()) {
            groups[_Custom.TYPE_INTENTION].push(custom);
        }
    };

    var appendCustom = function (custom) {
        var customs = _cache.customs;
        customs.push(custom);
        _pushCustomToGroup(_cache.custom_groups, custom);
        saveCustomData(customs);
    };

    var getCustomGroupByType = function (type) {
        return type === _Custom.TYPE_NONE ? _cache.customs : _cache.custom_groups[type];
    };

    return{
        loadCustomData:loadCustomData,
        saveCustomData:saveCustomData,
        computeCustomGroup:computeCustomGroup,
        appendCustom:appendCustom,
        getCustomGroupByType:getCustomGroupByType
    }

})(App);